import React,{Component,View,StyleSheet,Text,ListView,LayoutAnimation,UIManager,RefreshControl,ToastAndroid} from 'react-native';
import Bw from './bw';
//颜色
import * as MColor from '../../designColor/meterialColor';
//reduce
import {bindActionCreators} from 'redux';
import * as mainScreenActions from '../../actions/mainScreenActions';
import { connect } from 'react-redux';

//为了通过scroll的监听确定，当前页面显示到哪里，需要明确listview里面的节头高度，和每一个list的高度
const SECTION_HEAD_HIGHT=30;//节头的高度
const LIST_HIGHT=80;//每一个list的高度


class bwlist extends Component {
  //==========================构造函数====================================================
  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({
      sectionHeaderHasChanged: (r1, r2) => r1 !== r2,
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    var data=this.props.reduxbwlist
    var sectionID=this.getObjectkey(data);
    //LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
    this.state={
      ifStartLogin:false,//指示是否开始login，只有这个值为真的时候，才会当props接收到fetchstate=='success'，进行跳转
      isRefreshing:false,//代表是否显示下拉时出现的圆圈
      sectionID:sectionID,
      dataSource: ds.cloneWithRowsAndSections(data, sectionID),
      //section的位置信息
      sectionPostion:this.calSectionScrollPostion(data, sectionID,SECTION_HEAD_HIGHT,LIST_HIGHT)
    }
  }
  /*===================================得到对象的key数组=========================*/
  getObjectkey(ob){
    var result=[];
    for(var key in ob){
      result.push(key)
    };
    return result;
  }
  /*根据确定的节头高度，list高度，计算出每一段节头属于的scroll位置
    //    var data={
    //     A:['高','梁','南','奉','大','高','梁','南','奉','大'],
    //     B:['高','梁','南','奉','大','高','梁','南','奉','大']
    //    };
    //    var sectionID=['A','B'];
          sectionHight section头的高度  const SECTION_HEAD_HIGHT=100;
          listHight list的高度 const LIST_HIGHT=80
    返回 [0, 820, 1640, 2460]代表scroll在哪里是第几个section
  */
  //============================计算出每一段节头属于的scroll位置=================================================
  calSectionScrollPostion(data,sectionID,sectionHight,listHight){
    var result=[];
    result.push(0);//第一个section在0的位置
    for (var sec in data) {
      //console.log(data[sec]);
      var sectionlong=data[sec].length*listHight+sectionHight;
      //最后一个值再加上这个section的长度
      result.push(result[result.length-1]+sectionlong);
    };
    return result;
  }
  //==========================单击进入bwlist===========================================================
  onSelect=()=>{
    this.props.navigator.push({
      name: 'bwList'
    });
  };
  //===========================渲染组头=============================================
  renderSectionHeader(sectionData,sectionID){
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.sectionHeaderText}>{sectionID}</Text>
      </View>
    );
  };
  //=====================滚动监听事件===========================================
  onScroll=(event)=>{
    //console.log('当前位置'+event.nativeEvent.contentOffset.y);
    var positiony=event.nativeEvent.contentOffset.y
    for (var i = 0; i < this.state.sectionPostion.length-1; i++) {
      //判断在哪个setion中
      if (this.state.sectionPostion[i]<= positiony && positiony<=this.state.sectionPostion[i+1]) {
        //如果topbar的farmunit和section里面的不一样，通过redux改变
        if (this.props.reduxFarmunit!=this.state.sectionID[i]) {
          this.props.reduxChangeFarmunit(this.state.sectionID[i]);
        };
        //this.props.reduxChangeFarmunit(i);
        break;//已经找到在那个头里面了，不用再判断
      };
    };
  };
  //=============当props改变的时候,如果fetch成功，就路由跳转===============================
  componentWillReceiveProps(nextprops){
    if(this.state.ifStartLogin){//只有下拉时才会触发响应开关   
      if(nextprops.mapstate_fetchstate=='success'){
        ToastAndroid.show('刷新成功', ToastAndroid.SHORT)
        this.setState({isRefreshing: false,ifStartLogin:false});//不显示圈圈，不可以触发跳转的动作
      };
      if(nextprops.mapstate_fetchstate=='error'){
        ToastAndroid.show('刷新失败', ToastAndroid.SHORT)
        this.setState({isRefreshing: false,ifStartLogin:false});//不显示圈圈，不可以触发跳转的动作
      }
    }
  }
  //===================下拉刷新==========================================
  _onRefresh() {
    this.setState({isRefreshing: true,ifStartLogin:true});//先显示下拉的圆圈,可以响应redux中fetch的状态变化
    this.props.reduxFetchManinscreenData('http://10.33.51.107:28017/bw800golang/paraStruct/');
  }

  //=========================渲染==================================
  render() {
    var ds = new ListView.DataSource({
      sectionHeaderHasChanged: (r1, r2) => r1 !== r2,
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    // var data=this.props.reduxbwlist
    // var sectionID=this.getObjectkey(data);
    //这里设置一个状态是为了让onscroll使用
    // this.setState={
    //   sectionID:sectionID,
    //   sectionPostion:this.calSectionScrollPostion(data, sectionID,SECTION_HEAD_HIGHT,LIST_HIGHT)
    // }
    return (
      <ListView
        style={styles.contain}
                refreshControl={
          <RefreshControl
            refreshing={this.state.isRefreshing}
            onRefresh={this._onRefresh.bind(this)}
            tintColor="#ff0000"
            title="Loading..."
            titleColor="#00ff00"
            colors={['white', 'lightblue', 'lightgreen']}
            progressBackgroundColor="grey"
          />
        }
        automaticallyAdjustContentInsets={false}
        //dataSource={ds.cloneWithRows(this.state.dataSource)}
        dataSource={ds.cloneWithRowsAndSections(this.props.reduxbwlist, this.getObjectkey(this.props.reduxbwlist))}
        onScroll  ={this.onScroll}
        renderSectionHeader={this.renderSectionHeader}
        renderRow={(rowData,sec,index) => <Bw
                                            secName={sec}
                                            mapstate_ifTestmode={this.props.mapstate_ifTestmode}
                                            reduxEnterFarmunit={this.props.reduxEnterFarmunit}
                                            reduxFetchDayRecordDataByAddr={this.props.reduxFetchDayRecordDataByAddr}
                                            LIST_HIGHT={LIST_HIGHT}
                                            navigator={this.props.navigator}
                                            rowData={rowData} 
                                            index={index}>
                                          </Bw>}
        //renderHeader={(e)=>this._renderHeader(e)}
      ></ListView>
        
    );
  }
}

const styles = StyleSheet.create({
  contain:{
    flex:1,
    //backgroundColor:'red',

  },
  sectionHeader: {
    height:SECTION_HEAD_HIGHT,
    //backgroundColor: '#48D1CC',
    backgroundColor:MColor.ACCENT_COLOR,
    paddingLeft: 30,
    justifyContent:'center',

  },
  sectionHeaderText: {
    fontFamily: 'AvenirNext-Medium',
    fontSize: 16,
    color: 'white',
    paddingLeft: 10
  },
});

//将全局state绑定到组件的props中
function mapStateToProps(state) {
  return { 
    //state字段key
    mapstate_ifTestmode:state.mainScreenRedux.system.ifTestmode,//指示fetch的状态
    mapstate_fetchstate:state.mainScreenRedux.system.fetchstate,//指示fetch的状态
    reduxbwlist:state.mainScreenRedux.mainscreen.bwlist,
    reduxFarmunit:state.mainScreenRedux.mainscreen.farmunit,
    //mapstate: state.mainScreenRedux.system,//在上面的组件实例化时存入 
  }
}

//绑定一个方法到props中
function mapDispatchToProps(dispatch) {
  var mapaction=bindActionCreators(mainScreenActions, dispatch);
  return {
    reduxChangeFarmunit:mapaction.reduxChangeFarmunit,
    reduxEnterFarmunit:mapaction.reduxEnterUnit,
    reduxFetchManinscreenData:mapaction.reduxFetchManinscreenData,
    reduxFetchDayRecordDataByAddr:mapaction.reduxFetchDayRecordDataByAddr,//拉取更新日下料记录
    //mapactions: bindActionCreators(mainScreenActions, dispatch) 
  }
}

//将全局的state绑定到组件中
export default connect(mapStateToProps,mapDispatchToProps)(bwlist);